package com.blog.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.Utils.Result;
import com.blog.bean.domain.Chapter;
import com.blog.bean.dto.ChapterDTO;
import com.blog.bean.vo.ChapterVO;
import com.blog.mapper.ChapterMapper;
import com.blog.service.ChapterService;
import com.blog.service.CourseVideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 任浩
 * @version 1.0
 */

@Slf4j
@Service
public class ChapterServiceImpl implements ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private CourseVideoService courseVideoService;

    /**
     * 新增章节
     * @param chapterDTO
     * @return
     */
    @Transactional
    @Override
    public Result add(ChapterDTO chapterDTO) {
        if (chapterDTO == null || chapterDTO.getName() == null || "".equals(chapterDTO.getName())){
            return Result.error("章节名称不能为空");
        }
        if (chapterDTO.getCourseId() == null){
            return Result.error("课程id不能为空");
        }

        Chapter chapter = new Chapter();
        chapter.setName(chapterDTO.getName());
        chapter.setCourseId(chapterDTO.getCourseId());
        if(chapterDTO.getParent() == null){
            chapter.setParent(0);
        }
        else {
            chapter.setParent(chapterDTO.getParent());
        }

        chapterMapper.insert(chapter);

        return Result.success(chapter.getId());
    }

    @Override
    public Result getByCourseId(Integer id) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", id).eq("del",0);
        List<Chapter> chapters = chapterMapper.selectList(queryWrapper);
        List<Map<String,Object>> res = new ArrayList<>();

        //过滤出是父章节的视频。
        List<Chapter> collect = chapters.stream().filter(data -> data.getParent() == 0)
                                                    .collect(Collectors.toList());

        collect.forEach(item ->{
            List<ChapterVO> collect1 = chapters.stream().filter(data -> data.getParent().intValue() == item.getId().intValue())
                                .map(data -> new ChapterVO(data.getId(), data.getName(),null))
                                .collect(Collectors.toList());
            Map<String, Object> map = new HashMap<>();
            map.put("name",item.getName());
            map.put("id",item.getId());
            map.put("children",collect1);
            res.add(map);
        });

        //根据课程id，查询该课程下的视频。
        Result<List<Map<String, Object>>> courseVideo = courseVideoService.getByCourseId(id);
        List<Map<String, Object>> courseVideoList = courseVideo.getData();

        //为章节添加视频列表
        res.forEach(item ->{
            List<ChapterVO> children = (List<ChapterVO>) item.get("children");

            if(children == null || children.stream().count() == 0){
                log.info("此时没有子章节，只有父章节");
                //此时没有子标签
                Integer chapterId = Integer.parseInt(item.get("id").toString());
                courseVideoList.forEach(data ->{
                    if((chapterId.intValue() == Integer.parseInt(data.get("chapterId").toString()))){
                        item.put("children",data.get("children"));
                    }
                });
            }
            else{
                log.info("此时包含子章节");
                children.forEach(data ->{
                    courseVideoList.forEach(video ->{
                        if((data.getId().intValue() == Integer.parseInt(video.get("chapterId").toString()))){
                            data.setChildren(video.get("children"));
                        }
                    });
                });
            }
        });

        log.info("根据课程查找的章节列表为: {}",res);

        return Result.success(res);
    }

    @Override
    public Result getChapter(Integer id) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", id).eq("del",0);
        List<Chapter> chapters = chapterMapper.selectList(queryWrapper);
        List<Map<String,Object>> res = new ArrayList<>();

        //过滤出是父章节的视频。
        List<Chapter> collect = chapters.stream().filter(data -> data.getParent() == 0)
                .collect(Collectors.toList());

        collect.forEach(item ->{
            List<ChapterVO> collect1 = chapters.stream().filter(data -> data.getParent().intValue() == item.getId().intValue())
                    .map(data -> new ChapterVO(data.getId(), data.getName(),null))
                    .collect(Collectors.toList());
            Map<String, Object> map = new HashMap<>();
            map.put("label",item.getName());
            map.put("value",item.getId());

            //没有子组件，自动添加一个。
            if(collect1.stream().count() == 0){
                Map<String,Object> child = new HashMap<>();
                child.put("label",item.getName());
                child.put("value",item.getId());
                List<Map<String,Object> > childList = new ArrayList<>();
                childList.add(child);
                map.put("children",childList);
            }
            res.add(map);
        });

        return Result.success(res);

    }
}
